package tracingservice

import (
	"alarmservice/model"
	"alarmservice/service"
	"time"
)

type TriggerTracing struct {
	Tracing
}

func NewTriggerTracing(modelTracing *model.Tracing) (*TriggerTracing, error) {
	t := new(TriggerTracing)
	t.Id = modelTracing.Id
	t.Model = modelTracing
	return t, nil
}

func (t *TriggerTracing) Trigger(data string) error {
	warningCacheKey := "wcache" + t.Model.Key + data
	wc, ok := service.Cache.Get(warningCacheKey)
	if ok {
		//用来更新请求报警id
		warningId := wc.(int64)
		_, err := model.Orm.Where("id=?", warningId).Incr("num").Update(model.Warning{})
		if err != nil {
			return err
		}
	} else {
		//新建触发并发送推送信息
		w := model.NewWarning(t.Model.ProjectId, t.Model.Id, data)

		err := model.Insert(w)
		if err != nil {
			return err
		}


		service.Cache.Add(warningCacheKey, w.Id, time.Minute*15) //15分钟内相同的报警就不重复触发了
		
		err = t.SendWarningMsg()
		if err != nil {
			return err
		}
	}
	
	return nil
	
}


func (t *TriggerTracing) Disabled() error {
	return nil
}

func (t *TriggerTracing) Enabled() error {
	return nil
}